/**
 * 此云对象主要用于快速获取支付宝和微信支付证书的序列号
 * 作者：VK
 */
const fs = require('fs');
const antcertutil = require("alipay-sdk/lib/antcertutil");
const x509 = require('@fidm/x509');
module.exports = {
	/**
	 * 获取微信支付证书的序列号
	 */
	getWxPaySN({ appCert }) {
		let res = { errCode: 0 };
		try {
			let appCertSn = getSN(appCert).toUpperCase();
			res.appCertSn = appCertSn;
		} catch (err) {
			if (err.message.indexOf("invalid base64") > -1) {
				err.message += "（证书错误，请将你的 apiclient_cert.pem 放在test1/wxpay 目录下）"
			}
			return { errCode: -1, errMsg: err.message };
			console.error("微信支付证书序列号失败", err.message);
		}
		return res;
	},
	/**
	 * 获取支付宝证书的序列号
	 */
	getAlipaySN({ appCert, alipayRootCert }) {
		let res = { errCode: 0 };
		try {
			let appCertSn = antcertutil.getSN(appCert, false);
			let alipayRootCertSn = antcertutil.getSN(alipayRootCert, true);
			res.appCertSn = appCertSn;
			res.alipayRootCertSn = alipayRootCertSn;
		} catch (err) {
			if (err.message.indexOf("invalid base64") > -1) {
				err.message += "（证书错误，请将你的 alipayRootCert.crt 和 appCertPublicKey.crt 放在test1/alipay 目录下）"
			}
			console.error("获取支付宝证书的序列号失败", err.message);
			return { errCode: -1, errMsg: err.message };
		}
		return res;
	}
}

function getSN(fileData) {
	if (typeof fileData == 'string') {
		fileData = Buffer.from(fileData);
	}
	let certificate = x509.Certificate.fromPEM(fileData);
	return certificate.serialNumber;
}
